﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media.Animation;

namespace Gronia.WPF.Controls
{
    public partial class PageTransition : Control
    {
        public PageTransition()
        {
            this.CreateAnimations();
        }

        static PageTransition()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(PageTransition), new FrameworkPropertyMetadata(typeof(PageTransition)));
        }

        private ContentControl ContentControl;

        public void Load(UserControl page)
        {
            if (Content != null)
            {
                UserControl oldpage = Content as UserControl;
                if (oldpage != null)
                {
                    oldpage.Loaded -= PageLoaded;
                    Unload(page);
                }
            }
            else
            {
                page.Loaded += PageLoaded;
                Content = page;
            }
        }

        protected void Unload(UserControl page)
        {
            Storyboard board = OutAnimations[TransitionType];
            board.Completed += delegate
            {
                page.Loaded += PageLoaded;
                Content = page;
            };
            board.Begin(ContentControl);
        }

        private void PageLoaded(object sender, RoutedEventArgs e)
        {
            Storyboard board = InAnimations[TransitionType];
            board.Begin(ContentControl);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            ContentControl = GetTemplateChild("ContentControl") as ContentControl;
        }
    }
}